package com.lagou.client;

import com.lagou.boot.ConsumerBoot;
import com.lagou.handler.JSONSerializer;
import com.lagou.handler.RpcEncoder;
import com.lagou.handler.UserClientHandler;
import com.lagou.request.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消费者
 */
public class RPCConsumer {

    //1.创建一个线程池对象  -- 它要处理我们自定义事件
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /**
     * 存储服务端和最后一次请求的响应时间
     */
    public static Map<String, Long> serverToResponseTime = new HashMap<>();

    /**
     * 存储服务端和最后一次请求的系统时间
     */
    public static Map<String, Long> serverToLastTime = new HashMap<>();

    /**
     * 村粗服务端和UserClientHandler的映射关系
     */
    public static Map<String, UserClientHandler> clientMap = new HashMap<>();

    /**
     * 获取UserClientHandler
     */
    public static UserClientHandler getClient(String address) throws InterruptedException {
        if(clientMap.get(address) != null){
            return clientMap.get(address);
        }
        return initClient(address);
    }

    //3.编写方法,初始化客户端  ( 创建连接池  bootStrap  设置bootstrap  连接服务器)
    public synchronized static UserClientHandler initClient(String address) throws InterruptedException {
        //1) 初始化UserClientHandler
        UserClientHandler userClientHandler  = new UserClientHandler();
        //2)创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //3)创建客户端的引导对象
        Bootstrap bootstrap =  new Bootstrap();
        //4)配置启动引导对象
        bootstrap.group(group)
                //设置通道为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY,true)
                //监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
        String[] serverAddress = address.split(":");
        bootstrap.connect(serverAddress[0], Integer.parseInt(serverAddress[1])).sync();
        clientMap.put(address, userClientHandler);
        return userClientHandler;
    }

    //4.编写一个方法,使用JDK的动态代理创建对象
    // serviceClass 接口类型,根据哪个接口生成子类代理对象;
    public static Object createProxy(final Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                        try{
                            //获取要调用的服务地址
                            String address = ConsumerBoot.getServerAddress();
                            System.out.println(address);
                            //1)初始化客户端cliet
                            UserClientHandler userClientHandler = getClient(address);

                            //2)给UserClientHandler 设置param参数
                            RpcRequest rpcRequest = new RpcRequest();
                            rpcRequest.setClassName(serviceClass.getName());
                            rpcRequest.setMethodName(method.getName());
                            rpcRequest.setParameters(objects);
                            rpcRequest.setParameterTypes(method.getParameterTypes());
                            rpcRequest.setRequestId(UUID.randomUUID().toString());
                            userClientHandler.setParam(rpcRequest);

                            //3).使用线程池,开启一个线程处理处理call() 写操作,并返回结果
                            long begin = System.currentTimeMillis();
                            Object result = executorService.submit(userClientHandler).get();
                            long end = System.currentTimeMillis();

                            //记录最后一次请求的响应时间和系统时间
                            serverToLastTime.put(address, end);
                            serverToResponseTime.put(address, end-begin);

                            //4)return 结果
                            return result;
                        }catch (Exception e){
                            return "";
                        }

                    }
                });
    }


}
